#Using Qt in Python
Qt is a cross-platform graphical user interface framework. The current main versions are Qt5 and Qt6, with Qt5 no longer maintained.
In Python, there are two Qt6 packages: PyQt6
(third-party) and PySide6
(official Qt release). Their usage is almost identical.
#Installation
Install PySide6
with the following command:
pip install PySide6
#Basic Example
The following code creates a simple GUI program with a label and a button. Each time the button is clicked, the number on the label increases by one.
import sys
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QWidget,
QLabel,
QPushButton,
QVBoxLayout,
)
class Widget(QWidget):
'''
Widget serves as the central widget of the window
'''
def __init__(self):
'''
Constructor
'''
# Call superclass constructor
super().__init__()
# Counter variable
self.__count = 0
# Create a label to display text
self.__label = QLabel(f"Count: {self.__count}")
# Create a button for clicking
self.__button = QPushButton("Click Me")
# Connect signal: when button clicked, call self.increase
self.__button.clicked.connect(self.increase)
# Create layout
self.__layout = QVBoxLayout()
self.__layout.addWidget(self.__label)
self.__layout.addWidget(self.__button)
self.setLayout(self.__layout)
def increase(self):
'''
Increase increments count and updates label
'''
self.__count += 1
self.__label.setText(f"Count: {self.__count}")
if __name__ == "__main__":
app = QApplication(sys.argv) # Create application
window = QMainWindow() # Create main window
widget = Widget() # Create widget
window.setCentralWidget(widget) # Set central widget
window.show() # Show window
app.exec() # Run program, returns when window closes
#Qt Main Window Layout
QMainWindow
provides a basic framework for building application user interfaces:
- Menu Bar — menu bar
- Toolbars — toolbars, can have multiple
- Dock Widgets — dockable widgets attached to the window edges, resizable and movable, can have multiple
- Central Widget — the central widget responsible for the main functionality of the window
- Status Bar — status bar, used to display status information
#Qt Layout System
Every Qt widget can have its own layout. Common layouts include horizontal layout (QHBoxLayout
), vertical layout (QVBoxLayout
), and grid layout (QGridLayout
).
import sys
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QWidget,
QPushButton,
QVBoxLayout,
QHBoxLayout,
QGridLayout
)
class Widget(QWidget):
'''
Widget serves as the central widget of the window
'''
def __init__(self):
'''
Constructor
'''
super().__init__()
# Horizontal layout example
self.__hbox = QHBoxLayout()
self.__hbox.addWidget(QPushButton("hbox 1"))
self.__hbox.addWidget(QPushButton("hbox 2"))
self.__hbox.addWidget(QPushButton("hbox 3"))
# Vertical layout example
self.__vbox = QVBoxLayout()
self.__vbox.addWidget(QPushButton("vbox 1"))
self.__vbox.addWidget(QPushButton("vbox 2"))
self.__vbox.addWidget(QPushButton("vbox 3"))
# Grid layout example
self.__grid = QGridLayout()
self.__grid.addWidget(QPushButton("grid 1"), 0, 0)
self.__grid.addWidget(QPushButton("grid 2"), 0, 1)
self.__grid.addWidget(QPushButton("grid 3"), 1, 0)
self.__grid.addWidget(QPushButton("grid 4"), 1, 1)
# Layouts can contain layouts
self.__main_layout = QVBoxLayout()
self.__main_layout.addLayout(self.__hbox)
self.__main_layout.addLayout(self.__vbox)
self.__main_layout.addLayout(self.__grid)
self.setLayout(self.__main_layout)
if __name__ == "__main__":
app = QApplication(sys.argv) # Create application
window = QMainWindow() # Create main window
widget = Widget() # Create widget
window.setCentralWidget(widget) # Set central widget
window.show() # Show window
app.exec() # Run program, returns when window closes
#Qt Signals and Slots
Qt’s Signal & Slot mechanism is one of the core features of the Qt framework. It enables communication between objects, similar to event listeners but more powerful, flexible, and safe than traditional callbacks.
Usage: when a signal is emitted, the connected slot is called.
# Connect signal and slot
object.signal.connect(slot)
# Disconnect signal and slot
object.signal.disconnect(slot)
# Emit signal
object.signal.emit()
To define a custom signal, the class must inherit from QObject
. The signal is created as a class attribute:
class Widget(QWidget): # QWidget inherits from QObject, so no need to inherit QObject again
my_signal = Signal() # Create signal
#Qt Styling
Qt uses QSS (similar to CSS) for styling. Widgets call setStyleSheet
with a QSS string to set styles.
The style structure is as follows:
selector { property: value; property: value; property: value; }
- Selector determines which widgets are affected, e.g.,
QLabel
,QPushButton
. - Properties and values specify styles, e.g.,
background-color: red
sets the background to red.
Adding styles to the basic example code:
def __init__(self):
# ... omitted for brevity
# Set stylesheet
self.setStyleSheet('''QWidget {
background-color: #2b2b2b;
color: #eeeeee;
font-size: 16px;
font-family: "Microsoft YaHei";
}
QLabel {
font-weight: bold;
padding: 5px;
color: #f0f0a0;
}
QPushButton {
background-color: #3c3f41;
border: 1px solid #555;
border-radius: 5px;
padding: 8px 16px;
color: #ffffff;
}
QPushButton:hover {
background-color: #505354;
}
QPushButton:pressed {
background-color: #2c2f30;
}
''')
Common properties:
Category | Property Name | Example Value | Description |
---|---|---|---|
Font | font-size | 16px | Font size |
- | font-family | "Microsoft YaHei" | Font family |
- | font-weight | normal , bold , 100~900 | Font weight |
- | font-style | normal , italic | Font style |
- | color | #ffffff | Font color |
Background | background-color | #2b2b2b , transparent | Background color |
- | background-image | url(:/images/bg.png) | Background image |
- | background-repeat | no-repeat , repeat-x | Background repeat mode |
- | background-position | center , top left | Background position |
Border | border | 1px solid #ccc | Border style |
- | border-width | 1px | Border width |
- | border-style | solid , dashed , none | Border style |
- | border-color | #ff0000 | Border color |
- | border-radius | 5px | Border radius (rounded corners) |
Padding & Margin | padding | 5px | Padding (inner spacing) |
- | margin | 5px | Margin (outer spacing) |
Size | min-width | 100px | Minimum width |
- | max-height | 50px | Maximum height |
- | width | 200px | Fixed width |
- | height | 200px | Fixed height |